package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Result;
import com.example.common.ResultCode;
import com.example.dao.AdminInfoDao;
import com.example.entity.Account;
import com.example.entity.AdminInfo;
import com.example.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminIfoService {

    @Resource
    private AdminInfoDao adminInfoDao;
    public Account login(String name,String password){

        //通过用户名和密码去数据库里查一条数据
        AdminInfo adminInfo=adminInfoDao.findByNameAndPassword(name,password);

        if(ObjectUtil.isEmpty(adminInfo)){
            throw new CustomException("-1","用户名、密码或角色错误");
        }

        return  adminInfo;
    }
    public AdminInfo findById(long id){
        return adminInfoDao.findById(id);
       // return adminInfoDao.selectByPrimaryKey(id);

    }

    public void update(AdminInfo adminInfo){
        //adminInfoDao.updateByPrimaryKeySelective(adminInfo);
        adminInfoDao.updateById(adminInfo.getId(),adminInfo.getName(),adminInfo.getPassword(),adminInfo.getSex(),adminInfo.getAge(),adminInfo.getPhone(),adminInfo.getLevel());
    }

    public void add(AdminInfo adminInfo) {
        // 插入数据库要考虑完整性原则
        //1.新增的管理员如果没有密码要默认一个
        //2.管理员虽然不是主键，但是不能重名，否则不好登录

        //查询是否重名
        AdminInfo info=adminInfoDao.findByName(adminInfo.getName());
        if(ObjectUtil.isNotEmpty(info)){
            throw  new CustomException(ResultCode.USER_EXIST_ERROR);
        }
        //默认密码为123456
        if(ObjectUtil.isEmpty(adminInfo.getPassword())){
            adminInfo.setPassword("123456");

        }
        if(ObjectUtil.isEmpty(adminInfo.getLevel())) {
            adminInfo.setLevel(1);
        }
        adminInfoDao.insertSelective(adminInfo);
    }

    public List<AdminInfo> findALL() {
        return adminInfoDao.selectAllAdmin();
    }

    public void deleteById(Long id) {
  //     adminInfoDao.deleteByPrimaryKey(id);
        adminInfoDao.deleteById(id);
    }

    public PageInfo<AdminInfo> findPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<AdminInfo > infos = adminInfoDao.selectAllAdmin();
        return PageInfo.of(infos);
    }

    public PageInfo<AdminInfo> findPageName(Integer pageNum, Integer pageSize ,String name) {
        PageHelper.startPage(pageNum,pageSize);
        List<AdminInfo> infos =adminInfoDao.findByNamePage(name);
        return PageInfo.of(infos);
    }
}
